import { citys } from './citys';
import axios from "axios";
const fs = require("fs")


const main = async () => {
    // let data = await axios({ method: "GET", url: getInUrl("632200"), responseType: "json" })
    // let indata = data.data.replace("cb(", "").replace(")", "")
    // await fs.writeFileSync(`./data/in${"632200"}.json`, unescape(indata.replace(/\\/g, '%')))
    for await (const iterator of citys) {
        let data = await axios.get(getInUrl(iterator.item_code))
        let fdata = data.data.replace("cb(", "").replace(")", "")
        await fs.writeFileSync(`./data/${iterator.item_code}in.json`,unescape(fdata.replace(/\\/g, '%')))
        console.log(`保存in${iterator.item_name}`)
        data= await axios.get(getOutUrl(iterator.item_code))
        fdata = data.data.replace("cb(", "").replace(")", "")
        await fs.writeFileSync(`./data/${iterator.item_code}out.json`,unescape(fdata.replace(/\\/g, '%')))
        console.log(`保存out${iterator.item_name}`)
        // await asleep(10)
    }
}

// 迁入url
function getInUrl(id: string) {
    return `https://huiyan.baidu.com/migration/cityrank.jsonp?dt=province&id=${id}&type=move_in&date=20210404`
}

// 迁出url
function getOutUrl(id: string) {
    return `https://huiyan.baidu.com/migration/cityrank.jsonp?dt=province&id=${id}&type=move_out&date=20210404`

}

// 暂停时间 秒
async function asleep(timeout: number) {
    return new Promise<void>(r => {
        setTimeout(() => {
            r()
        }, timeout * 1000);
    })
}

main()